// index.js
// 获取应用实例
const app = getApp()
const requests = require("../../utils/request")

Page({
  data: {
    //static
    minBack:'',
    noLogin:'',

    kaipin:false,
    // showContent:false,
    totalHeight:app.globalData.navigationBarHeight+app.globalData.statusBarHeight,

    kaipin1:'',
    kaipin2:'',

    slide_up1:null,

    motto: 'Hello World',
    defaultAvator:"../../imgs/addEassy.png",
    defaultUserName:"未知用户",
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    titles:["我的居民卡","我的邀请","我的礼券"],
    icons:[".././../imgs/pointIcon.png",".././../imgs/pointIcon.png",".././../imgs/pointIcon.png",],
    navigateTo:[],
    rank:0,
    rankAdd:0,
    weightSum:0,
    weightAdd:0,
    canIUseGetUserProfile: false,
    openid:"",
    gotOpenid:false,
    cells1:[
        {
          "icon":"../../imgs/indexGrid/scan.png",
          "title":"垃圾投递订单",
          "url":"../order/index",
          "isTabbar":true,
          "active":0
        },
        {
          "icon":"../../imgs/indexGrid/doorService.png",
          "title":"垃圾上门订单",
          "url":"../order/index",
          "isTabbar":true,
          "active":1
        },
        {
          "icon":"../../imgs/jifenduihuan.png",
          "title":"礼品兑换订单",
          "url":"../order/index",
          "isTabbar":true,
          "active":2
        },
        {
          "icon":"../../imgs/tabbar/discover.png",
          "title":"我的动态",
          "url":"../mine/myEassy/index",
          "isTabbar":false
        },
        {
          "icon":"../../imgs/myaddress.png",
          "title":"我的地址",
          "url":"../mine/myAddress/index",
          "isTabbar":false
        },
    ],
    cells2:[
      {
        "icon":"../../imgs/help.png",
        "title":"帮助中心",
        "url":"../helpCenter/index",
        "isTabbar":false
      },
      {
        "icon":"../../imgs/us.png",
        "title":"关于我们",
        "url":"./aboutUs/index",
        "isTabbar":false
      },
    ]
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  skipAnimation()
  {
    this.setData({
      kaipin:false
    })
  },
 async onLoad() {

  this.setData({
    kaipin:true
  })

  
    //下载静态图片资源
    let res1 = await requests.downloadFile('static/kaipin2.png')
    let res2 = await requests.downloadFile('static/kaipin1.png')
    this.setData({
      kaipin2:res1,
      kaipin1:res2,
    })


    setTimeout(()=>{
      app.show(this, 'slide_up1', 1)
    },500)
    setTimeout(()=>{
      app.slideupshow(this, 'slide_up1', 100 , 1)
    },2000)
    setTimeout(()=>{
      app.show(this, 'slide_up1', 0)
    },3500)

    setTimeout(()=>{
      app.show(this, 'slide_up2', 1)
    },5500)
    // setTimeout(()=>{
    //   app.slideupshow(this, 'slide_up2', 100 , 1)
    // },9000)
    setTimeout(()=>{
      app.sliderightshow(this,'slide_up2',app.globalData.sysWidth,0)
      // app.show(this, 'slide_up2', 0)
    },7500)

    var that = this
    if (this.data.kaipin) {
      setTimeout(()=>{
        that.setData({
          kaipin: false
        })
      },10500)
    }
  //   setTimeout(()=> {
  //     app.show(this, 'slide_up3',1)
  //  }, 12500);

    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }


  
    let res3 = await requests.downloadFile('static/pleaseLogin.png')
    let res4 = await requests.downloadFile('static/mine-back.png')
    let res5 = await requests.downloadFile('static/mine-pleaselogin.png')
    this.setData({
        noLogin:res3,
        minBack:res4,
        noLogin:res5
      })



    wx.login({
      success: async (res)=> {
        //获取code
        console.log(res)
        //获取openid
        // let res1 = await requests.getOpenId(res.code)
        const res1 = await wx.cloud.callContainer({
          path:`/container-trashrecycle-core/api/sys/core/user/login?code=${res.code}&tag=0`,
          method: 'GET',
        })
        console.log(res1)
        const openid = res1.data.data.value
        console.log(openid)
        if(openid)
        {
        this.setData({
          openid,
          gotOpenid:true
        })


        //获取用户默认的地址
        requests.getAddressByOrder(openid).then((res)=>{
          // console.log(res.data.data.value)
          let addressList = res.data.data.value
          if(addressList.length>0&&addressList[0].isdefault==1)
          {
            wx.setStorage({
              key:"address",
              data:addressList[0]
            })
          }
        })


      }
    }
    })
// this.test()
    // console.log(app.globalData)
    if (app.globalData.userInfo) {
      /*
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      */
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      /*
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
      */
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      /*
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
      console.log(this.data.userInfo)
      */
    }
  },
  onShow()
  {

   
   

  },
  getUserInfo:async function(e) {
    // console.log("旧版本getUserInfo")
    // console.log(e)
    var that = this
    if(this.data.gotOpenid)
    {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })

                const openid = this.data.openid
                app.globalData.openid=openid
                //新增或更新
                let alreadyHadUser =await  requests.getUserById(openid)
                // console.log(alreadyHadUser.data.data.value)
                const {integration,trashWeight} = alreadyHadUser.data.data.value
                const {avatarUrl,nickName}= this.data.userInfo
                
                this.setData({
                  rank:integration?integration:0,
                  weightSum:trashWeight?trashWeight:0
                })
                
                if(alreadyHadUser.data.data.value)
                {
                  //更新信息
                  // app.globalData.userInfo.integration = alreadyHadUser.data.data.value.
                   requests.userInterface(avatarUrl,null,nickName,this.data.openid,null,null,null,this.data.openid,"update")
                }else
                {
                  //新增用户
                  // console.log(this.data.userInfo)
                  // requests.userInterface(avatarUrl,0,nickName,this.data.openid,0,null,0,null,"add")
                }


    }
  },

  ongetUserProfile(e) {
// console.log("新方法getUserProfile")
// console.log(this.data.openid)
    if(this.data.gotOpenid)
    {
    // console.log(this.data.gotOpenid)

        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        console.log('获取资料')
        wx.getUserProfile({
          desc: '用于完善资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success:async (res) => {
          //获取用户信息
            console.log('用户信息',res)
            app.globalData.userInfo = res.userInfo
            // console.log(app.globalData)
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
        
          // const avatarUrl = res.userInfo.avatarUrl
          const openid = this.data.openid
          app.globalData.openid=openid
          // console.log(avatarUrl)
          //新增或更新
          let alreadyHadUser =await  requests.getUserById(openid)
          // console.log('alreadyHadUser',alreadyHadUser.data.data.value)
          const {integration,trashWeight} = alreadyHadUser.data.data.value
          const {avatarUrl,nickName}= this.data.userInfo
          
          this.setData({
            rank:integration?integration:100,
            weightSum:trashWeight?trashWeight:0
          })
          
          if(alreadyHadUser.data.data.value)
          {
            //更新信息
            // app.globalData.userInfo.integration = alreadyHadUser.data.data.value.
             let res = await requests.userInterface(avatarUrl,this.data.rank,nickName,this.data.openid,null,null,null,this.data.openid,"update")
            console.log('updateUser',res.data.data.value)
          }else
          {
            //新增用户
            console.log(this.data.userInfo)
            // requests.userInterface(avatarUrl,0,nickName,this.data.openid,0,null,0,null,"add")
          }

          },
          fail:(err)=>{
            console.log('获取资料失败',err)
          }
        })
      }
      else
      {
        wx.showToast({
          title: '网络延迟',
          icon: 'error',
          duration: 2000
        })
        wx.login({
          success: async (res)=> {
            //获取code
            console.log(res)
            //获取openid
            // let res1 = await requests.getOpenId(res.code)
            const res1 = await wx.cloud.callContainer({
              path:`/container-trashrecycle-core/api/sys/core/user/login?code=${res.code}&tag=0`,
              method: 'GET',
            })
            // console.log(res1)
            const openid = res1.data.data.value
            console.log(openid)
            if(openid)
            {
            this.setData({
              openid,
              gotOpenid:true
            })
          }
          else
          {
            wx.showToast({
              title: '获取openid失败',
              icon: 'error',
              duration: 2000
            })

          }
        
        }

})
      }
    }
  })
